package com.ferry.config.server.controller;

import com.ferry.config.server.LongPollManager;
import com.ferry.config.server.service.FConfigItemService;
import com.ferry.config.server.vo.FConfigItemDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by daiyong
 */
@RestController
@RequestMapping("/fConfigServer")
public class ConfigController {

	private static final Map<String, Object> result = new HashMap<>();

	static {
		result.put("code", 0);
		result.put("msg", "");
		result.put("data", null);
	}

	@Autowired
	private FConfigItemService fConfigItemService;

	@RequestMapping("/get")
	public Object get(String nameSpace) {
		List<FConfigItemDO> items = fConfigItemService.get(nameSpace);
		List<Map<String, Object>> maps = new ArrayList<>();
		for (FConfigItemDO item : items) {
			Map<String, Object> map = new HashMap<>();
			map.put("key", item.getfKey());
			map.put("content", item.getContent());
			map.put("utime", item.getuTime());
			maps.add(map);
		}
		return maps;
	}

	/**
	 * 长轮询 60s超时时间
	 * @param nameSpace
	 * @return
	 */
	@RequestMapping("/longPoll")
	public Object longPoll(String nameSpace, long maxUtime) {

		/**
		 * 1 首先查询是否在创建长链接时有修改, 如果有修改 直接返回，否则hang住
		 */
		List<FConfigItemDO> items = fConfigItemService.getByMaxUtime(nameSpace, maxUtime);

		if (!CollectionUtils.isEmpty(items)) {
			List<Map<String, Object>> maps = new ArrayList<>();
			for (FConfigItemDO item : items) {
				Map<String, Object> map = new HashMap<>();
				map.put("key", item.getfKey());
				map.put("content", item.getContent());
				map.put("utime", item.getuTime());
				maps.add(map);
			}
			return maps;
		} else {
			DeferredResult<String> deferredResult = new DeferredResult<>(60000L, new ResponseEntity<>(HttpStatus.NOT_MODIFIED));
			LongPollManager.addDeferredResult(nameSpace, deferredResult);
			return deferredResult;
		}


	}

	@RequestMapping("/create")
	public Object create(
			String nameSpace,
			String key,
			String content,
			String cUser,
			String desc
	) {
		fConfigItemService.create(nameSpace, key, content, cUser, desc);
		return result;
	}

	@RequestMapping("/update")
	public Object update(
			String nameSpace,
			String key,
			String content,
			String uUser,
			String desc
	) {
		fConfigItemService.update(nameSpace, key, content, uUser, desc);
		return result;
	}
}
